package com.jnu.myllm.server.impl;

import com.jnu.myllm.entity.Record;
import com.jnu.myllm.entity.User;
import com.jnu.myllm.mapper.RecordMapper;
import com.jnu.myllm.mapper.UserMapper;
import com.jnu.myllm.server.RecordService;
import com.jnu.myllm.ui.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class RecordServiceImpl implements RecordService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RecordMapper recordMapper;
    // 事务（transaction）加在业务层，对数据会有影响的才加
    @Override
    @Transactional
    public Result addRecord(String question, String answer, int tokens, int userId) {
        Record r = new Record();
        r.setUserId(userId);
        r.setTokens(tokens);
        r.setPay(0);
        int pay = 0;
        // 超过五条开始消耗积分，每100个token消耗1积分
        int count = recordMapper.selectCountByDate(new Date(), userId)+1;
        System.out.println("您今日已经使用了"+count+"次");
        if(count > 5){
            pay = tokens/100;
        }
        r.setPay(pay);
        User u = userMapper.selectByUid(userId);
        // 判断积分是否足够
        if(u.getScore()<pay){
            throw new RuntimeException("积分不足");
        }
        u.setScore(u.getScore()-pay);
        r.setQuestion(question);
        r.setAnswer(answer);
        if (userMapper.update(u)==0){
            return new Result(5001,"数据库错误：该用户不存在",null);
        } else if (recordMapper.deleteByUser(u.getId())==0) {
            return new Result(5002,"数据库错误：记录更新失败",null);
        }else if (recordMapper.insertrecord(r)==0){
            return new Result(5003,"数据库错误：插入记录失败",null);
        }else{
            return new Result(2000,"插入记录成功",null);
        }
    }
    @Override
    public List<Record> selectByUser(int userId) {
        return recordMapper.selectByUser(userId);
    }
    @Override
    public int queryCountByToday(int userId) {
        return recordMapper.selectCountByDate(new Date(), userId);
    }
}
